import React, { useState, useEffect } from 'react';


export default function SortSellers() {
    const [needResort, setNeedResort] = useState(true);
    const [recentSellerInfoList, setRecentSellerInfoList] = useState([
        {"seller_id": 212, "seller_name": 'berserk 2'},
        {"seller_id": 515, "seller_name": 'archer 5'},
        {"seller_id": 313, "seller_name": 'counter 3'},
        {"seller_id": 121, "seller_name": 'master 1'},
        {"seller_id": 490, "seller_name": 'darker 4'}
    ]);

    function handleClick() {
        setNeedResort(!needResort);
    }

    useEffect(() => {
        console.log('needResort: ', needResort);
        if (needResort) {
            // 按recent排序
            const recent = '["121:master 1", "212:berserk 2", "313:counter 3", "490:darker 4", "515:archer 5"]';
            if (recent !== null && recent.length > 0) {
                let sellerMap = new Map();
                JSON.parse(recent).forEach((seller, index) => {
                    const sellerId = seller.split(':')[0];
                    sellerMap.set(sellerId, index);
                })
                // console.log('sellerMap: ', sellerMap); // console.log('before sort: ', recentSellerInfoList) // 因为state机制，log出来还是旧数据，注释掉
                recentSellerInfoList.sort((a, b) => {
                    const sellerIdA = a.seller_id;
                    const sellerIdB = b.seller_id;
                    // console.log('sellerIdA: ', sellerIdA, sellerMap.get(String(sellerIdA)), ' sellerIdB: ', sellerIdB, sellerMap.get(String(sellerIdB)))
                    return sellerMap.get(String(sellerIdA)) - sellerMap.get(String(sellerIdB));
                });
                setRecentSellerInfoList(recentSellerInfoList)
            }
        } else {
            recentSellerInfoList.sort((a, b) => b.seller_id - a.seller_id);
            setRecentSellerInfoList(recentSellerInfoList);
        }
    }, [needResort, recentSellerInfoList]);

    return (
        <ul style={{border: 'solid'}}>
            <h4><button onClick={handleClick}>点我按id{needResort ? '正序' : '倒序'}</button>recentSellerInfoList: </h4>
            {recentSellerInfoList.map((seller, index) => {
                return (
                    <li key={index}>
                        <span>id: {seller.seller_id}, name: {seller.seller_name}</span>
                    </li>
                );
            })}
        </ul>
    );
}
